package com.david.restfull.verify.advice;

import com.david.exception.BusinessRuntimeException;
import com.david.auth.pojo.api.AuthApi;
import com.david.auth.pojo.constants.AuthBiz;
import com.david.auth.pojo.query.TokenQuery;
import com.david.auth.pojo.result.R;
import com.david.restfull.verify.annotation.ApiTokenVerify;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 对注解就行拦截
 *
 * @author David
 * @Before 方法执行之前
 * @After 方法执行之后
 * @Around 方法执行前后
 * @AfterThrowing 抛出异常后
 * @AfterReturing 正常返回后
 */
@Aspect
@Component
public class ApiControllerAdvice {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private final static String AUTH = "Authorization";

    private final static String APP_KEY = "appKey";

    @Autowired
    private AuthApi authApi;


    /**
     * 拦截被ApiTokenVerify注解的方法
     *
     * @param point
     * @param apiTokenVerify
     * @throws Throwable
     */
    @Before("@annotation(apiTokenVerify)")
    public void beforeTest(JoinPoint point, ApiTokenVerify apiTokenVerify) throws Throwable {
        //获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //获取对象头中的这个信息
        String authorization = request.getHeader(AUTH);
        String appKey = request.getHeader(APP_KEY);

        if (StringUtils.isEmpty(authorization) || StringUtils.isEmpty(appKey)) {
            log.error("鉴权失败!无权限token或者appKey");
            throw new BusinessRuntimeException(AuthBiz.FAIL_AUTH);
        }

        TokenQuery tokenQuery = new TokenQuery();
        tokenQuery.setToken(authorization);
        tokenQuery.setAppKey(appKey);

        R<String> r = authApi.verifyToken(tokenQuery);
        if (!r.isOK()) {
            log.error("token验签失败!appKey:{},token:{}", appKey, authorization);
            throw new BusinessRuntimeException(AuthBiz.FAIL_AUTH_OVERDUE);
        }
    }


}
